<?php
App::import('Vendor', 'PHPExcel', array('file' => 'PHPExcel.php'));
App::import('Vendor', 'PHPExcel_Reader_Excel2007', array('file' => 'PHPExcel/Excel2007.php'));
App::import('Vendor', 'PHPExcel_IOFactory', array('file' => 'PHPExcel/PHPExcel/IOFactory.php'));

App::uses('AppController', 'Controller');
/**
 * Padres Controller
 *
 * @property Padre $Padre
 */
class PadresController extends AppController {

/**
 * index method
 *
 * @return void
 */
    public $layout = 'colegio';
    public $uses = array(
    'Alumno', 
    'Padre', 
    'AlumnosPadre', 
    'User', 
    'AlumnosParciale', 
    'Ciclo', 
    'AlumnosParalelo',
    'AlumnosPlanespago',
    'Alumnospago',
    'Pago', 
    'Periodo', 
    'Turno', 'Horario',
    'Excel'
    );
    public $components = array('Fechasconvert');
    
    public function beforeFilter()
    {
        parent::beforeFilter();
        $this->Auth->allow('*');
    }
    
	public function index() {
		$padres = $this->Padre->find('all', array('recursive'=>-1));
		$this->set(compact('padres'));
	}
    public function ajaxlistado()
    {
        //debug($this->request->data);exit;
        $this->layout = 'ajax';
            if(!empty($this->request->data['Padre']['nombre']) and empty($this->request->data['Padre']['ap_paterno']) and empty($this->request->data['Padre']['ap_materno']))
            {
                $padres = $this->Padre->find('all',array('conditions'=>array('Padre.nombre LIKE'=> '%'.$this->request->data['Padre']['nombre'].'%')));
            }
            if(!empty($this->request->data['Padre']['ap_paterno'])and empty($this->request->data['Padre']['nombre']) and empty($this->request->data['Padre']['ap_materno']))
            {
                $padres = $this->Padre->find('all',array('conditions'=>array('Padre.ap_paterno LIKE'=> '%'.$this->request->data['Padre']['ap_paterno'].'%')));
            }
            if(!empty($this->request->data['Padre']['ap_materno'])and empty($this->request->data['Padre']['nombre']) and empty($this->request->data['Padre']['ap_paterno']))
            {
                $padres = $this->Padre->find('all',array('conditions'=>array('Padre.ap_materno LIKE'=> '%'.$this->request->data['Padre']['ap_materno'].'%')));
            }
            if(!empty($this->request->data['Padre']['ap_materno'])and !empty($this->request->data['Padre']['nombre']) and empty($this->request->data['Padre']['ap_paterno']))
            {
                $padres = $this->Padre->find('all',array('conditions'=>array('Padre.ap_materno LIKE'=> '%'.$this->request->data['Padre']['ap_materno'].'%',
                'Padre.nombre LIKE'=> '%'.$this->request->data['Padre']['nombre'].'%')));
            }
            if(!empty($this->request->data['Padre']['ap_materno'])and empty($this->request->data['Padre']['nombre']) and !empty($this->request->data['Padre']['ap_paterno']))
            {
                $padres = $this->Padre->find('all',array('conditions'=>array('Padre.ap_materno LIKE'=> '%'.$this->request->data['Padre']['ap_materno'].'%',
                'Padre.ap_paterno LIKE'=> '%'.$this->request->data['Padre']['ap_paterno'].'%')));
            }
            if(empty($this->request->data['Padre']['ap_materno'])and !empty($this->request->data['Padre']['nombre']) and !empty($this->request->data['Padre']['ap_paterno']))
            {
                $padres = $this->Padre->find('all',array('conditions'=>array('Padre.ap_paterno LIKE'=> '%'.$this->request->data['Padre']['ap_paterno'].'%',
                'Padre.nombre LIKE'=> '%'.$this->request->data['Padre']['nombre'].'%')));
            }
            if(!empty($this->request->data['Padre']['ap_materno'])and !empty($this->request->data['Padre']['nombre']) and !empty($this->request->data['Padre']['ap_paterno']))
            {
                $padres = $this->Padre->find('all',array('conditions'=>array('Padre.ap_paterno LIKE'=> '%'.$this->request->data['Padre']['ap_paterno'].'%',
                'Padre.nombre LIKE'=> '%'.$this->request->data['Padre']['nombre'].'%',
                'Padre.ap_materno LIKE'=> '%'.$this->request->data['Padre']['ap_materno'].'%')));
            }
        $this->set(compact('padres'));
    }

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		$this->Padre->id = $id;
		if (!$this->Padre->exists()) {
			$this->Session->setFlash(__('Id del padre o tutor invalido'), 'msgerror');
            $this->redirect(array('action'=>'index'));
		}
		$this->set('padre', $this->Padre->read(null, $id));
	}
    public function guardaexcel()
    {
        //debug($this->request->data);die;
        $archivoExcel = $this->request->data['Excel']['excel'];
        $nombreOriginal = $this->request->data['Excel']['excel']['name'];


        if ($archivoExcel['error'] === UPLOAD_ERR_OK)
        {
            $nombre = string::uuid();
            if (move_uploaded_file($archivoExcel['tmp_name'], WWW_ROOT . 'files' . DS . $nombre . '.xlsx'))
            {
                $nombreExcel = $nombre . '.xlsx';
                $direccionExcel = WWW_ROOT . 'files';
                $this->request->data['Excelg']['nombre'] = $nombreExcel;
                $this->request->data['Excelg']['nombre_original'] = $nombreOriginal;
                $this->request->data['Excelg']['direccion'] = "";
                $this->request->data['Excelg']['tipo'] = "asignacion";
            }
        }
        if ($this->Excel->save($this->data['Excelg']))
        {
            $ultimoExcel = $this->Excel->getLastInsertID();
            //debug($ultimoExcel);die;
            $excelSubido = $nombreExcel;
            $objLector = new PHPExcel_Reader_Excel2007();
            //debug($objLector);die;
            $objPHPExcel = $objLector->load("../webroot/files/$excelSubido");
            //debug($objPHPExcel);die;

            $rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();

            $array_data = array();

            foreach ($rowIterator as $row)
            {
                $cellIterator = $row->getCellIterator();

                $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set

                if (1 == $row->getRowIndex()) //a partir de la 1
                    continue; //skip first row

                $rowIndex = $row->getRowIndex();

                $array_data[$rowIndex] = array(
                    'A' => '',
                    'B' => '',
                    'C' => '',
                    'D' => '',
                    'E' => '',
                    'F' => '',
                    'G' => '',
                    'H' => '',
                    'I' => '',
                    'J' => '',
                    'K' => '',
                    'L' => '');

                foreach ($cellIterator as $cell)
                {
                    if ('A' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    } elseif ('B' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    } elseif ('C' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    } elseif ('D' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    } elseif ('E' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    } elseif ('F' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }  elseif ('G' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    } elseif ('H' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }elseif ('I' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }elseif ('J' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }elseif ('K' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }elseif ('L' == $cell->getColumn())
                    {
                        $array_data[$rowIndex][$cell->getColumn()] = $cell->getCalculatedValue();
                    }
                }
            }

            $datos = array();
            $i = 0;
            $this->request->data = "";
            
            
            
            foreach ($array_data as $d)
            {
                $this->request->data[$i]['Padre']['nombre'] = $d['A'];
                $this->request->data[$i]['Padre']['ap_paterno'] = $d['B'];
                $this->request->data[$i]['Padre']['ap_materno'] = $d['C'];
                $this->request->data[$i]['Padre']['sexo'] =  $d['D'];
                $this->request->data[$i]['Padre']['estadocivil'] = $d['E'];
                $this->request->data[$i]['Padre']['ci'] = $d['F'];
                $this->request->data[$i]['Padre']['fechanacimiento'] = $d['G'];
                $this->request->data[$i]['Padre']['direccion'] = $d['H'];
                $this->request->data[$i]['Padre']['email'] = $d['I'];
                $this->request->data[$i]['Padre']['telefono'] = $d['J'];
                $this->request->data[$i]['Padre']['celular'] = $d['K'];
                $this->request->data[$i]['Padre']['observaciones'] = $d['L'];
                
                $i++;
            }
            //debug($this->data);
            //exit;
            if ($this->Padre->saveMany($this->data))
            {
                //echo 'registro corectamente';
                $this->Padre->deleteAll(array('Padre.nombre' => '')); //limpiamos el excel con basuras
                $this->Session->setFlash('se Guardo correctamente el EXCEL');
                $this->redirect(array('action' => 'index'));
            } else
            {
                echo 'no se pudo guardar';
            }
            //fin funciones del excel
        } else
        {

            //echo 'no';
        }
    }

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if (!empty($this->request->data)) {
			
            $this->Padre->create();
			$nombrecompleto = $this->request->data['Padre']['ap_paterno'].' '.$this->request->data['Padre']['ap_materno'].' '.$this->request->data['Padre']['nombre'];
            $usuario = $this->request->data['Padre']['ci'];
            $fecha = $this->request->data['Padre']['fechanacimiento'];
            $fechaNacimiento = $this->Fechasconvert->doCambiaFormato($fecha);
            $password = $this->Fechasconvert->doFechaPass($fecha);
           
            $this->request->data['Padre']['fechanacimiento'] = $fechaNacimiento;
            
            if ($this->Padre->save($this->request->data)) {
                $a=1;
            }else{
				$a=0;
			}
			 if($a){
			     
                  $idPadreCreado = $this->Padre->getLastInsertID();
			      
                  $this->request->data = "";
                  
                  $this->request->data['Users']['username'] = $usuario;
                  $this->request->data['Users']['password'] = $password;
                  $this->request->data['Users']['padre_id'] = $idPadreCreado;
                  $this->request->data['Users']['group_id'] = 4;
                               
                  if ($this->User->save($this->request->data['Users'])) {
                      
                     $this->Session->setFlash(__("Los datos fueron registrados!!! <br/> El usuario generado para el tutor/padre $nombrecompleto es: <br/>
                                        USUARIO: $usuario <br/>
                                        PASSWORD:$password

                                         "), 
                                        'msgbueno');
                    
                    $this->redirect(array('action' => 'index'));
                  }else {
                    $this->Session->setFlash('Padre NO guardado!!!', 'msgerror');
                    $this->redirect(array('action' => 'index'));
                  }
			 }else{
			     $this->Session->setFlash(__('El padre o tutor fue guardado'), 'msgbueno');
				 $this->redirect(array('action' => 'index'));
			 }
			
		}
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
	  
		$this->Padre->id = $id;
        
		if (!$this->Padre->exists()) {
			$this->Session->setFlash(__('Id del padre o tutor invalido'), 'msgerror');
            $this->redirect(array('action'=>'index'));
		}
		if (!empty($this->request->data)) {
			if ($this->Padre->save($this->request->data)) {
				$this->Session->setFlash(__('Los datos fueron guardados'), 'msgbueno');
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('El padre pudo editarse. Por favor, intente nuevamente.'), 'msgalert');
			}
		} else {
			$this->request->data = $this->Padre->read(null, $id);
		}
	}

/**
 * delete method
 *
 * @throws MethodNotAllowedException
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
	   $this->Padre->id = $id;
       
		if (!$this->Padre->exists()) {
			$this->Session->setFlash(__('Id del padre o tutor invalido'), 'msgerror');
            $this->redirect(array('action'=>'index'));
		}
        $tutelas = $this->AlumnosPadre->find('count', array('conditions'=>array('AlumnosPadre.padre_id'=>$id)));
        if($tutelas != 0){
            $this->Session->setFlash(__('Este padre o tutor tiene alumnos a su tutela y no puede ser eliminado!!'), 'msgalert');
			$this->redirect(array('action' => 'index'));
        }
		if ($this->Padre->delete()) {
			$this->Session->setFlash(__('Padre o tutor eliminado'), 'msgbueno');
			$this->redirect(array('action' => 'index'));
		}
		$this->Session->setFlash(__('Padre no se elimino'), 'msgerror');
		$this->redirect(array('action' => 'index'));
	}
    public function asignalumno($id=null){
        $padre = $this->Padre->find('first', array('recursive'=>-1, 'conditions'=>array('Padre.id'=>$id)));
        $alumnos = $this->Alumno->find('all', array(
        'fields'=>array('Alumno.id', 'Alumno.ap_paterno', 'Alumno.ap_materno', 'Alumno.nombre'),
        'recursive'=>-1));
        if(!empty($this->request->data)){
            
            $datos = $this->request->data;            
            foreach($datos['alumnos'] as $dato){
                $this->request->data="";
                $this->request->data['AlumnosPadre']['alumno_id'] = $dato;
                $this->request->data['AlumnosPadre']['padre_id']= $id;
                $this->AlumnosPadre->create();
                
                $this->AlumnosPadre->save($this->request->data);
            }
            
            $this->Session->setFlash(__('Alumnos de tutela asignados'), 'msgbueno');
            $this->redirect(array('action' => 'vertutela', $id));
        }
        $this->set(compact('alumnos', 'padre'));
        
    }
    public function vertutela($id=null){
        $listatutela = $this->AlumnosPadre->find('all', array(
        'conditions'=>array('AlumnosPadre.padre_id'=>$id),
        'recursive'=>2, 
        'fields'=>array(
                'Padre.id','Padre.nombre', 'Padre.ap_paterno', 'Padre.ap_materno', 
                'Alumno.nombre', 'Alumno.ap_paterno', 'Alumno.ap_materno',
                'AlumnosPadre.id','AlumnosPadre.created'
            )
        ));
        
        $padre = $this->Padre->find('first', array('recursive'=>-1, 'conditions'=>array('Padre.id'=>$id)));
        $this->set(compact('listatutela', 'padre'));
    }
    public function vernotas($idAlumno=null, $gestion=null){
        $notas = $this->AlumnosParciale->find('all',array(
            'conditions'=>array(
                'AlumnosParciale.alumno_id'=>$idAlumno, 
                'AlumnosParciale.gestion'=>$gestion, 
                'AlumnosParciale.promedio !='=>0),
                
            'order'=>array('Materia.orden ASC')
        ));
        //debug($notas);
        $ciclos = $this->Ciclo->find('all', array(
            'conditions'=>array('Ciclo.gestion'=>$gestion),
            'recursive'=>-1
        ));
        $alumno = $this->AlumnosParalelo->find('first', array(
           'conditions'=>array('AlumnosParalelo.alumno_id'=>$idAlumno)
        ));
        $this->set(compact('notas', 'ciclos', 'alumno', 'gestion'));
    }
    
    public function verestadocuentas($idAlumno=null, $gestion=null){
        
        $this->layout = 'ajax';
        $alumno = $this->Alumno->find('first', array('conditions'=>array('Alumno.id'=>$idAlumno), 
                'recursive'=>-1
        ));
        //debug($alumno);
        $nombre = $alumno['Alumno']['ap_paterno'].' '.$alumno['Alumno']['ap_materno'].' '.$alumno['Alumno']['nombre'];
        $planes = $this->AlumnosPlanespago->find('list', array(
            'conditions' => array('AlumnosPlanespago.alumno_id' => $idAlumno,
                    'AlumnosPlanespago.gestion' => $gestion),
            'fields' => array('AlumnosPlanespago.planespago_id'),
            'recursive' => -1));
        
        $fecha = '%' . date('Y') . '%';

        $yapagados = $this->Alumnospago->find('list', array(
            'conditions' => array(
                    'Alumnospago.alumno_id' =>$idAlumno, 
                    'Alumnospago.fecha LIKE' => $fecha), 
            'fields' => array('Alumnospago.pago_id')));
        
        $pagos = $this->Pago->find('all', array('conditions' => array('Pago.planespago_id' =>
                    $planes), 'order' => array('Pago.nombre ASC')));
        
        $c = 0;
        foreach ($pagos as $pago) {
            $a = 0;
            foreach ($yapagados as $pagado) {
                if ($pago['Pago']['id'] == $pagado) {
                    $pagos[$c]['Pago']['pagado'] = 1;
                    $a = 1;
                }
            }
            if (!$a) {
                $pagos[$c]['Pago']['pagado'] = 0;
            }
            $c++;
        }
        //debug($pagos);
        $this->set(compact('planes', 'pagos', 'idAlumno', 'nombre'));
    }
    public function panel(){
        $idPadre = $this->Session->read('Auth.User.padre_id');
        $datosPadre = $this->Padre->find('first',array(
                'conditions'=>array('Padre.id'=>$idPadre),
                'recursive'=>-1
            ));
        //debug($datosPadre);
        $this->set(compact('idPadre', 'datosPadre'));
    }
    public function verhorarios(){
        $gestion = date("Y");
        
        $idPadre = $this->Auth->user('padre_id');
       
        $listatutela = $this->AlumnosPadre->find('all', array(
            'recursive' => 0, 
            'conditions' => array(
                'AlumnosPadre.padre_id' => $idPadre
            )));
        $this->set(compact('listatutela', 'gestion'));
    }
    public function horario($idAlumno=null, $gestion = null){
        $this->layout = 'ajax';
        
        $paralelo = $this->AlumnosParalelo->find('first', array(
                    'conditions'=>array('AlumnosParalelo.alumno_id'=>$idAlumno, 'AlumnosParalelo.gestion'=>$gestion)
            ));
        $idParalelo = $paralelo['AlumnosParalelo']['paralelo_id'];
        $periodos = $this->Periodo->find('all', array(
                        'conditions' => array('Turno.gestion' =>$gestion), 
                        'order' => array('Periodo.turno_id  ASC', 'Periodo.periodo ASC')));
        
        $turnos = $this->Turno->find('all', array('conditions' => array('Turno.gestion' =>
                    $gestion)));
       $horarios = $this->Horario->find('count', array(
                           'conditions'=>array(
                                'Horario.paralelo_id'=>$idParalelo,
                                'Horario.gestion'=>$gestion),
                           'recursive'=>-1
                        ));
       $alumno = $this->Alumno->find('first', array('conditions'=>array('Alumno.id'=>$idAlumno), 
                'recursive'=>-1
        ));
        //debug($alumno);
        $nombre = $alumno['Alumno']['ap_paterno'].' '.$alumno['Alumno']['ap_materno'].' '.$alumno['Alumno']['nombre'];
        
        $this->set(compact('idParalelo', 'periodos', 'turnos', 'horarios', 'gestion', 'nombre'));
    }
}
